package org.spider.core.utils;

import lombok.extern.slf4j.Slf4j;
import org.spider.api.executor.ShapeExecutor;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
@Slf4j
//ApplicationContextAware 解决Executor静态变量注入问题
public class ExecutorsUtils implements ApplicationContextAware {
    //静态字段不能直接注入
    private static List<ShapeExecutor> executors;
    private static Map<String,ShapeExecutor> executorMap;
    private static ApplicationContext applicationContext;
    //通过构造函数来初始化
    @Autowired
    private ExecutorsUtils(List<ShapeExecutor> executors){
        ExecutorsUtils.executors = executors;
    }
    @PostConstruct
    private void pc(){
        executorMap = executors.stream().collect(Collectors.toMap(k->k.supportShape(),v->v));
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        ExecutorsUtils.applicationContext = applicationContext;
    }

    public static ShapeExecutor get(String shape){
        return executorMap.get(shape);
    }
}
